/// <summary>
/// Copyright 2010 Ivo Limmen (ivo@limmen.org)
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
/// 
/// http://www.apache.org/licenses/LICENSE-2.0
/// 
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </summary>

using System;
using System.Text.RegularExpressions;
using Model = Services.Configuration.Model;
using Services.Configuration.Api;

namespace Services.Configuration
{
	public class VariableSettingResolver : IResolver
	{
		private IResolver configuration;
		
		public VariableSettingResolver (Model.Configuration configuration)
		{
			if (configuration == null) 
			{
				throw new ArgumentException("No Configuration provided!");
			}
			if (configuration.IsEmpty()) 
			{
				throw new ArgumentException("Empty Configuration provided!");
			}
			
			this.configuration = configuration;
		}

		#region IResolver implementation
		
		public string GetSetting (string hostname, string section, string key)
		{								
			return ReplaceVariables(hostname, this.configuration.GetSetting(hostname, section, key));
		}

		private string ReplaceVariables(string hostname, string setting) 
		{
			if (setting != null) 
			{
				Regex regexp = new Regex("\\${[a-z.-]*}");
				
				MatchCollection matches = regexp.Matches(setting);
				
				foreach (Match match in matches)
				{
					string reference = match.Value;

					if (reference != null)
					{
						string sectionKey = reference.Substring(2);
						sectionKey = sectionKey.Substring(0, sectionKey.Length - 1);
						string[] tokens = sectionKey.Split('.');
						
						setting = setting.Replace(reference, this.configuration.GetSetting(hostname, tokens[0], tokens[1]));
					}
				}
			}
			
			return setting;
		}
		
		#endregion
	}
}
